import os.path

from PySide6 import QtWidgets, QtCore
from PySide6.QtWidgets import QFileDialog

from src.ui.ui.MainWindow_ui import Ui_MainWindow
from src.utils.file_listening import IronManListening
from src.utils.logger import Logger
from src.configure import conf

logger = Logger(__name__)


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    update_signal = QtCore.Signal()
    listener: IronManListening = None

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("钢铁雄心铁人模式存档管理器")

        self.actionlistening_directory.triggered.connect(self.select_directory)

        self.widget.item_click_signal.connect(lambda x: self.update_file_record_widget(x))

        self.update_signal.connect(self.widget.refresh)
        self.update_signal.connect(self.widget_2.refresh)
        self.update_signal.emit()

        self.listening()

    def update_file_record_widget(self, src_path):
        self.widget_2.set_path(src_path)

    def listening(self):

        if self.listener is not None:
            self.listener.stop()
        self.listener = IronManListening(conf.listening_path, self.update_signal)
        self.listener.set_daemon(True)
        self.listener.start()

    def select_directory(self):
        path = QFileDialog.getExistingDirectory(self, '选择要记录存档的文件夹', conf.listening_path)
        # 将这个提取到的目录存储到数据库
        if os.path.exists(path):
            logger.i(path)
            conf.listening_path = path

